package com.lyf.controll;

import cn.hutool.json.JSONObject;
import com.lyf.result.Code;
import com.lyf.result.Result;
import com.lyf.service.impl.UserServiceImpl;
import com.lyf.pojo.User;
import com.lyf.service.UserService;
import com.lyf.utils.CrossRegion;
import com.lyf.utils.PageModel;
import com.lyf.utils.ResponseResult;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "UserControll", urlPatterns =
        {"/user/selectAll","/user/selectById","/user/UpdateOrAdd","/user/updateStatus","/user/updatePassword","/user/updatePasswordByFind",
         "/user/queryUsers","/user/queryUsers2","/user/deleteById","/user/findPassword"})
public class UserControll extends HttpServlet {
    UserService userService = new UserServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决跨域
//        CrossRegion.setCross(resp);
//        resp.setContentType("text/html;charset=utf-8");
//        req.setCharacterEncoding("utf-8");
        UserService userService = new UserServiceImpl();
        String servletPath = req.getServletPath();
        System.out.println("请求路径："+servletPath);
        if(servletPath.equals("/user/findPassword")){
            String loginname = req.getParameter("loginname");
            String phone = req.getParameter("phone");
            String code = req.getParameter("code");
            User user = userService.findPassword(loginname, phone);
            if(user != null){
                //到redis获取验证码信息
                Jedis jedis = new Jedis("127.0.0.1",6379);
                jedis.auth("123456");
                String checkCode = jedis.get("checkCode");
                if(code.equals(checkCode)){
                    Result result = new Result(Code.OK,user,"身份验证成功！");
                    ResponseResult.sendResult(resp,result);
                }else{
                    Result result = new Result(Code.Fail,null,"验证码错误！");
                    ResponseResult.sendResult(resp,result);
                }
            }else{
                Result result = new Result(Code.Fail,null,"身份验证失败！");
                ResponseResult.sendResult(resp,result);
            }
        } else if(servletPath.equals("/user/deleteById")){
            String id = req.getParameter("id");
            userService.delete(Integer.parseInt(id));

            Map<String,Object> map = new HashMap<>();

            Result result = new Result(Code.OK,null,"删除成功！");

            JSONObject jo = new JSONObject();
            map.put("result",result);
            jo.putAll(map);
            resp.getWriter().println(jo.toString());//响应到浏览器
        }
        else if(servletPath.equals("/user/UpdateOrAdd")){
            String id = req.getParameter("id");
            if(id != null){
                //修改
                String username = req.getParameter("username");
                String loginname = req.getParameter("loginname");
                String img = req.getParameter("img");
                String phone = req.getParameter("phone");
                String isdelete = req.getParameter("isdelete");
                String role = req.getParameter("role");
                String status = req.getParameter("status");
                String email = req.getParameter("email");

                User user = new User();
                user.setUsername(username);
                user.setLoginname(loginname);
                user.setImg(img);
                user.setPhone(phone);
                user.setIsdelete(Integer.parseInt(isdelete));
                user.setRole(Integer.parseInt(role));
                user.setStatus(Integer.parseInt(status));
                user.setId(Integer.parseInt(id));
                user.setEmail(email);

                userService.update(user);

                Map<String,Object> map = new HashMap<>();
                Result result = new Result(Code.OK,null,"修改成功！");
                JSONObject jo = new JSONObject();

                map.put("result",result);
                jo.putAll(map);
                //响应到浏览器
                resp.getWriter().println(jo.toString());

            }else{
                //新增
                String username = req.getParameter("username");
                String loginname = req.getParameter("loginname");
                String password = req.getParameter("password");
                String img = req.getParameter("img");
                String phone = req.getParameter("phone");
                String role = req.getParameter("role");
                String status = req.getParameter("status");
                // 获取当前时间
                LocalDateTime createdate = LocalDateTime.now();

                User user = new User();
                user.setUsername(username);
                user.setLoginname(loginname);
                user.setPassword(password);
                user.setImg(img);
                user.setPhone(phone);
                user.setCreateDate(createdate);
                user.setRole(Integer.parseInt(role));
                user.setStatus(Integer.parseInt(status));

                try{
                    userService.add(user);
                    Map<String,Object> map = new HashMap<>();
                    Result result = new Result(Code.OK,null,"用户添加成功！");
                    JSONObject jo = new JSONObject();

                    map.put("result",result);
                    jo.putAll(map);
                    //响应到浏览器
                    resp.getWriter().println(jo.toString());
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }else if(servletPath.equals("/user/updateStatus")){
            String id = req.getParameter("id");
            String status = req.getParameter("status");
            userService.updateStatus(Integer.parseInt(id),Integer.parseInt(status));

            Map<String,Object> map = new HashMap<>();
            Result result = new Result(Code.OK,null,"修改成功！");
            JSONObject jo = new JSONObject();

            map.put("result",result);
            jo.putAll(map);
            //响应到浏览器
            resp.getWriter().println(jo.toString());
        }
        else if(servletPath.equals("/user/selectById")){
            String id = req.getParameter("id");
            User user = userService.selectById(Integer.parseInt(id));

            Map<String,Object> map = new HashMap<>();
            Result result = new Result(Code.OK,user,"查询成功！");
            JSONObject jo = new JSONObject();

            map.put("result",result);
            jo.putAll(map);
            //响应到浏览器
            resp.getWriter().println(jo.toString());
        }else if(servletPath.equals("/user/updatePassword")){
            String loginname = req.getParameter("loginname");
            String password = req.getParameter("password");
            String id = req.getParameter("id");
            String newPassword = req.getParameter("newPassword");

            User user = userService.login(loginname, password);
            if(user == null){
                Map<String,Object> map = new HashMap<>();
                Result result = new Result(Code.Fail,null,"旧密码错误！");
                JSONObject jo = new JSONObject();

                map.put("result",result);
                jo.putAll(map);
                //响应到浏览器
                resp.getWriter().println(jo.toString());
            }else{
                userService.updatePassword(newPassword,Integer.parseInt(id));
                Map<String,Object> map = new HashMap<>();
                Result result = new Result(Code.OK,user,"密码修改成功！");
                JSONObject jo = new JSONObject();

                map.put("result",result);
                jo.putAll(map);
                //响应到浏览器
                resp.getWriter().println(jo.toString());
            }
        } else if(servletPath.equals("/user/updatePasswordByFind")){
            String id = req.getParameter("id");
            String newPassword = req.getParameter("newPassword");

                userService.updatePassword(newPassword,Integer.parseInt(id));
                Map<String,Object> map = new HashMap<>();
                Result result = new Result(Code.OK,null,"密码重置成功！");
                JSONObject jo = new JSONObject();

                map.put("result",result);
                jo.putAll(map);
                //响应到浏览器
                resp.getWriter().println(jo.toString());

        } else if(servletPath.equals("/user/queryUsers")){
            //获得当前页码
            String pageIndex = req.getParameter("pageNum");
            //获取每页显示条数
            String pageSize = req.getParameter("pageSize");

            //当前页码
            int pageNum = Integer.parseInt(pageIndex);
            //每页显示条数
            int pageSize2 = Integer.parseInt(pageSize);

            //设置到PageModel
            PageModel model = new PageModel();
            model.setPageIndex(pageNum);
            model.setPageSize(pageSize2);

            //获取查询条件
            String loginname = req.getParameter("loginname");
            String status = req.getParameter("status");


            //查询用户列表
            List<User> users = null;
            User user = new User();
            if(!loginname.equals("") && !loginname.isEmpty()){
                user.setLoginname(loginname);
            }
            if(!status.equals("") && !status.isEmpty()){
                int status2 = Integer.parseInt(status);
                user.setStatus(status2);
            }
            //总记录数
            int count = userService.getTotalUserCount(user);
            model.setTotalRecoreSum(count);
            users = userService.queryUsers(user,model);

            Map<String,Object> map = new HashMap<>();
            map.put("model",model);
            System.out.println("model:"+model);
            map.put("data",users);

            System.out.println("***************");
            for (User user1 : users) {
                System.out.println(user1);
            }
            System.out.println("***************");

            JSONObject jo = new JSONObject();
            jo.putAll(map);
            resp.getWriter().println(jo.toString());//响应到浏览器
        }
        else if(servletPath.equals("/user/queryUsers2")){
            //获得当前页码
            String pageIndex = req.getParameter("pageNum");
            //获取每页显示条数
            String pageSize = req.getParameter("pageSize");

            //当前页码
            int pageNum = Integer.parseInt(pageIndex);
            //每页显示条数
            int pageSize2 = Integer.parseInt(pageSize);

            //设置到PageModel
            PageModel model = new PageModel();
            model.setPageIndex(pageNum);
            model.setPageSize(pageSize2);

            //获取查询条件
            String loginname = req.getParameter("loginname");
            String status = req.getParameter("status");


            //查询用户列表
            List<User> users = null;
            User user = new User();
            if(!loginname.equals("") && !loginname.isEmpty()){
                user.setLoginname(loginname);
            }
            if(!status.equals("") && !status.isEmpty()){
                int status2 = Integer.parseInt(status);
                user.setStatus(status2);
            }
            //总记录数
            int count = userService.getTotalUserCount(user);
            model.setTotalRecoreSum(count);
            users = userService.queryUsers2(user,model);

            Map<String,Object> map = new HashMap<>();
            map.put("model",model);
            System.out.println("model:"+model);
            map.put("data",users);

            System.out.println("***************");
            for (User user1 : users) {
                System.out.println(user1);
            }
            System.out.println("***************");

            JSONObject jo = new JSONObject();
            jo.putAll(map);
            resp.getWriter().println(jo.toString());//响应到浏览器
        }
    }
}
